const toNumber = (value: string | undefined, fallback: number) => {
  if (!value) {
    return fallback;
  }

  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : fallback;
};

const toStringArray = (value: string | undefined) => {
  if (!value) {
    return [];
  }

  return value
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean);
};

export default () => ({
  app: {
    name: process.env.APP_NAME ?? "Business Overview API",
    env: process.env.NODE_ENV ?? "development",
    port: toNumber(process.env.PORT, 4000),
    globalPrefix: process.env.API_GLOBAL_PREFIX ?? "api",
    cors: {
      origins: toStringArray(process.env.CORS_ALLOWED_ORIGINS),
    },
  },
  database: {
    url: process.env.DATABASE_URL ?? "",
  },
  auth: {
    accessTokenSecret: process.env.JWT_ACCESS_TOKEN_SECRET ?? "",
    refreshTokenSecret: process.env.JWT_REFRESH_TOKEN_SECRET ?? "",
    accessTokenTtl: toNumber(process.env.JWT_ACCESS_TOKEN_TTL, 900),
    refreshTokenTtl: toNumber(process.env.JWT_REFRESH_TOKEN_TTL, 604800),
  },
  seed: {
    adminEmail: process.env.SEED_ADMIN_EMAIL ?? "admin@example.com",
    adminPassword: process.env.SEED_ADMIN_PASSWORD ?? "Admin123!",
  },
});
